import httpProxy from "http-proxy";
import { logger } from "./utils";

export function createProxy() {
  // 创建代理服务器
  const proxy = httpProxy.createProxyServer({});
  proxyRes(proxy);
  proxyError(proxy);
  return proxy;
}

/**
 * 请求处理
 * @param proxy
 */
function proxyRes(proxy) {
  // 缓存控制
  proxy.on("proxyRes", (proxyRes, req, res) => {
    // 对所有响应添加基本缓存控制
    proxyRes.headers["Cache-Control"] = "public, max-age=3600";

    // 对特定路径禁用缓存
    //   if (req.url.startsWith('/wscc/') || req.url.includes('/admin/')) {

    //   }
    proxyRes.headers["Cache-Control"] =
      "no-store, no-cache, must-revalidate, proxy-revalidate";
    proxyRes.headers["Pragma"] = "no-cache";
    proxyRes.headers["Expires"] = "0";
    // 对错误响应禁用缓存
    if (proxyRes.statusCode >= 400) {
      proxyRes.headers["Cache-Control"] = "no-store";
    }
  });
}

/**
 * 错误处理
 * @param proxy
 */
function proxyError(proxy) {
  // 错误处理
  proxy.on("error", (err, req, res) => {
    logger("❌代理错误:", "该模块可能出错:" + req.url + err.message);
    res.writeHead(500, { "Content-Type": "text/plain" });
    res.end("网关错误");
  });
}
